package com.timebank.volunteer.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.timebank.common.core.constant.cache.CacheConstant;
import com.timebank.common.core.result.Result;
import com.timebank.common.core.utils.StringUtils;
import com.timebank.common.core.utils.file.FileTypeUtils;
import com.timebank.common.core.utils.file.MimeTypeUtils;
import com.timebank.common.core.web.controller.BaseController;
import com.timebank.common.core.web.page.TableDataInfo;
import com.timebank.common.core.web.pojo.AjaxResult;
import com.timebank.common.log.annotation.Log;
import com.timebank.common.log.enums.BusinessType;
import com.timebank.common.security.annotation.RequiresLogin;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.system.pojo.SysFile;
import com.timebank.system.service.RemoteFileService;
import com.timebank.volunteer.pojo.dto.ExamineDTO;
import com.timebank.volunteer.pojo.dto.VolunteerDTO;
import com.timebank.volunteer.pojo.dto.VolunteerSignDTO;
import com.timebank.volunteer.pojo.entity.Volunteer;
import com.timebank.volunteer.pojo.vo.VolunteerVO;
import com.timebank.volunteer.service.VolunteerService;
import com.timebank.volunteer.service.VolunteerSignListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author shiliuyinzhen
 */
@RestController
@RequestMapping("/service")
@Api(tags = "志愿服务相关接口")
public class VolunteerController extends BaseController {

    @Resource
    private VolunteerService volunteerService;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource
    private VolunteerSignListService volunteerSignListService;

    /**
     * 根据id获取志愿服务信息
     * @param volunteerId
     * @return
     */
    @ApiOperation("根据id获取志愿服务信息")
    @GetMapping("/{volunteerId}")
    public Result<VolunteerVO> getVolunteerById(@PathVariable("volunteerId") Long volunteerId){
        return Result.success(volunteerService.getVolunteerById(volunteerId));
    }

    /**
     * 获取志愿服务列表
     *
     * @param volunteerDTO
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("获取志愿服务列表")
    public TableDataInfo list(VolunteerDTO volunteerDTO) {
        startPage();
        List<Volunteer> list = volunteerService.selectVolunteerList(volunteerDTO);
        return getDataTable(list);
    }

    /**
     * 新增志愿服务
     * @param volunteerDTO
     * @return
     */
    @RequiresLogin
    @Log(title = "志愿服务", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增志愿服务")
    public AjaxResult add(@RequestBody VolunteerDTO volunteerDTO) throws JsonProcessingException {
        return volunteerService.insertVolunteer(volunteerDTO);
    }

    /**
     * 批量删除志愿服务
     * @param volunteerIds
     * @return
     */
    @RequiresLogin
    @Log(title = "志愿服务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{volunteerIds}")
    @ApiOperation("根据ids删除志愿服务")
    public AjaxResult removeBatch(@PathVariable("volunteerIds") Long[] volunteerIds){
        return volunteerService.deleteVolunteerByIds(volunteerIds);
    }

    /**
     * 修改志愿服务封面
     * @param volunteerId
     * @param cover
     * @return
     */
    @RequiresLogin
    @Log(title = "志愿服务封面", businessType = BusinessType.UPDATE)
    @PutMapping("/cover/{volunteerId}")
    @ApiOperation("修改志愿服务封面")
    public AjaxResult updateVolunteer(@RequestBody String cover, @PathVariable("volunteerId") Long volunteerId){
        return toAjax(volunteerService.updateVolunteerCoverById(cover,volunteerId));
    }

    /**
     * 修改志愿服务信息
     * @param volunteerDTO
     * @return
     */
    @RequiresLogin
    @Log(title = "志愿服务", businessType = BusinessType.UPDATE)
    @PutMapping("/{volunteerId}")
    @ApiOperation("修改志愿服务信息")
    public AjaxResult update(@PathVariable("volunteerId")Long volunteerId, @RequestBody VolunteerDTO volunteerDTO) throws JsonProcessingException {
        return toAjax(volunteerService.updateVolunteerById(volunteerId, volunteerDTO));
    }

    /**
     * 报名志愿服务
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @Log(title = "报名志愿服务", businessType = BusinessType.INSERT)
    @PostMapping("/signUp/{volunteerId}")
    @ApiOperation("报名志愿服务")
    public AjaxResult signUpVolunteer(@PathVariable("volunteerId") Long volunteerId){
        return volunteerService.signUpVolunteer(volunteerId);
    }

    /**
     * 取消报名志愿服务
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @Log(title = "取消报名志愿服务", businessType = BusinessType.DELETE)
    @DeleteMapping("/signUp/{volunteerId}")
    @ApiOperation("取消报名志愿服务")
    public AjaxResult cancelSignUpVolunteer(@PathVariable("volunteerId") Long volunteerId){
        return volunteerService.cancelSignUpVolunteer(volunteerId);
    }

    /**
     * 获取已报名志愿服务列表
     * @return
     */
    @RequiresLogin
    @GetMapping("/signUp/list")
    @ApiOperation("获取已报名志愿服务列表")
    public TableDataInfo getSignUpVolunteerList(VolunteerDTO volunteerDTO){
        startPage();
        List<VolunteerVO> list = volunteerService.getSignUpVolunteerList(volunteerDTO);
        return getDataTable(list);
    }

    /**
     * 志愿服务封面上传
     */
    @RequiresLogin
    @Log(title = "志愿服务封面", businessType = BusinessType.INSERT)
    @PostMapping("/cover")
    @ApiOperation("志愿服务封面上传")
    public AjaxResult uploadCover(@RequestParam("coverfile") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            Result<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return error("文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", url);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }

    /**
     * 结束志愿服务
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @PostMapping("/end/{volunteerId}")
    @ApiOperation("结束志愿服务")
    public AjaxResult endVolunteer(@PathVariable("volunteerId") Long volunteerId){
        return volunteerService.endVolunteer(volunteerId);
    }

    /**
     * 开始签到
     * @param volunteerSignDTO
     * @return
     */
    @RequiresLogin
    @PostMapping("/sign/begin")
    @ApiOperation("开始签到")
    public AjaxResult beginSignIn(@RequestBody VolunteerSignDTO volunteerSignDTO){
        return toAjax(volunteerService.beginSignIn(volunteerSignDTO));
    }

    /**
     * 结束签到
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @DeleteMapping("/sign/end/{volunteerId}")
    @ApiOperation("结束签到")
    public AjaxResult endSignIn(@PathVariable("volunteerId") Long volunteerId){
        return toAjax(volunteerService.endSignIn(volunteerId));
    }

    /**
     * 志愿者签到
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @PostMapping("/user/sign/{volunteerId}")
    @ApiOperation("志愿者签到")
    public AjaxResult sign(@PathVariable("volunteerId") Long volunteerId){
        return volunteerSignListService.insertSignList(volunteerId);
    }

    /**
     * 检验是否签到
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @GetMapping("/sign/check/{volunteerId}")
    @ApiOperation("检验是否签到")
    public AjaxResult checkSign(@PathVariable("volunteerId")Long volunteerId){
        Long userId = SecurityUtils.getUserId();
        Boolean signStatus = volunteerSignListService.checkSign(volunteerId, userId);
        return signStatus ?
                AjaxResult.success("已经签到") : AjaxResult.error("未签到");
    }

    /**
     * 审核通过
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @PostMapping("/approve/{volunteerId}")
    @ApiOperation("审核通过")
    public AjaxResult approveVolunteer(@PathVariable("volunteerId") Long volunteerId){
        return volunteerService.approveVolunteer(volunteerId);
    }

    /**
     * 审核不通过
     * @param volunteerId
     * @return
     */
    @RequiresLogin
    @PostMapping("/fail/{volunteerId}")
    @ApiOperation("审核不通过")
    public AjaxResult failVolunteer(@PathVariable("volunteerId") Long volunteerId, @RequestBody ExamineDTO examineDTO){
        return volunteerService.failVolunteer(volunteerId,examineDTO);
    }

}
